<template>
  <el-card>
    <!-- 搜索 -->
    <el-form inline>
        <el-form-item>
            <el-input size="mini" v-model="searchName" placeholder="用户名" />
        </el-form-item>

        <el-button type="primary" size="mini" @click="search" icon="el-icon-search">查询</el-button>
        <el-button type="default" size="mini" @click="resetSearch" >清空</el-button>
    </el-form>

    <!-- 新增 -->
    <div style="margin: 20px 0">
      <el-button type="primary" size="mini" @click="showAddDialog" >添 加</el-button>
      <el-button type="danger" size="mini" :disabled="selectedList.length === 0" @click="deleteMoreAdmin" >批量删除</el-button>
    </div>

    <!-- 添加用户 -->
    <el-dialog
      :title="adminForm.id ? '修改用户' : '添加用户'"
      :visible.sync="admin.dialogVisible"
      width="50%">
      <span>
        <el-form label-width="100px" :model="adminForm" :rules="userRules" ref="adminForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="adminForm.username" size="mini" ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="adminForm.nickName" size="mini"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input type="password" v-model="adminForm.password" size="mini"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="admin.dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateAdmin" size="mini">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置角色 -->
    <el-dialog
      :visible.sync="role.dialogVisible"
      width="50%">
      <span>
        <el-form label-width="100px">
          <el-form-item label="用户名" >
            <el-input v-model="adminForm.username" size="mini" disabled ></el-input>
          </el-form-item>
          <el-form-item label="角色列表" >
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedList" @change="handleCheckedChange">
              <el-checkbox v-for="(item) in checkboxIdsList" :label="item.id" :key="item.id">{{item.roleName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="savRoleToUser">保存</el-button>
        <el-button @click="handleCancel" size="mini">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 用户管理列表 -->
    <el-table
        ref="selectedList"
        tooltip-effect="dark"
        :data="adminInfoList.items"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            type="index"
            label="序号"
            align="center"
            width="120">
        </el-table-column>
        <el-table-column
            prop="username"
            label="用户名">
        </el-table-column>
        <el-table-column
            prop="nickName"
            label="用户昵称">
        </el-table-column>
        <el-table-column
            prop="roleName"
            label="角色列表">
        </el-table-column>
        <el-table-column
            prop="gmtCreate"
            label="创建时间">
        </el-table-column>
        <el-table-column
            prop="gmtModified"
            label="更新时间">
        </el-table-column>
        <el-table-column
            label="操作"
            width="200">
            <template v-slot="{row}">
              <template>
                <el-button type="info" icon="el-icon-user" size="mini" @click="showRoleDialog(row)" title="分配角色"></el-button>
              </template>
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showUpdateDialog(row)" title="修改用户"></el-button>
              <el-popconfirm :title="`确定删除${row.username}`" @onConfirm="deleteAdmin(row.id)">
                <template #reference>
                  <el-button style="marginLeft: 10px" type="danger" icon="el-icon-delete" size="mini" title="删除用户"></el-button>
                </template>
              </el-popconfirm>
              
            </template>
        </el-table-column>
    </el-table>


    <!-- 分页器 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="getAdminInfoList"
      style="marginTop: 20px;"
      :current-page="current"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total">
    </el-pagination>


  </el-card>
</template>
<script>
import { mapGetters, mapState } from 'vuex';
import adminApi from '@/api/admin';
export default {
  name: 'User',
  data() {
    return {
      searchName: '',
      // 分页器
      current: 1,
      pageSize: 5,
      pageSizes: [5, 10, 15, 20],
      total: 0,
      // 用户对话框
      admin: {
        dialogVisible: false,
      },
      // 添加用户表单数据
      adminForm: {
        username: '',
        nickName: '',
        password: ''
      },
      // 批量删除收集选中要删的id
      selectedList: [],
      // 设置角色的对话框
      role: {
        dialogVisible: false
      },
      // 设置角色多选框
      // checkedItems: [],//绑定的每一项
      isIndeterminate: true,//表示 checkbox 的不确定状态
      checkAll: false,
      checkedList: [],//选择的id
      checkboxIdsList: [], //所有id
      // 表单验证
      userRules: {
        username: [
          { required: true, trigger: "blur", message: '品牌名称至少6位' },
        ],
        password: [
          { required: true, trigger: "blur", message: '密码至少6位' },
        ],
      }
      
    };
  },
  
  mounted(){
      // 1.获取用户管理分页列表
      this.getAdminInfoList();
  },
  
  methods: {
    // 1. 获取用户管理分页列表
    async getAdminInfoList(num = 1){
      this.current = num;
      // debugger
      let result = await this.$store.dispatch('admin/getAdminInfoList', {page: this.current, limit: this.pageSize, username: this.searchName});
      // console.log(result);
      this.total = result;
      // this.searchName = this.adminForm.username
    },
    // 改变每页数量
    handleSizeChange(size){
      this.pageSize = size;
      this.getAdminInfoList();
    },

    // 2. 添加用户
    showAddDialog(){
      this.admin.dialogVisible = true;
      this.adminForm = {
        username: '',
        nickName: '',
        password: ''
      }
    },
    // 3. 修改用户回显数据
    showUpdateDialog(row){
      // console.log(row);
      this.adminForm = {...row};
      this.admin.dialogVisible = true;
    },

    // dialog对话框点击确定, 发请求, 添加和修改的逻辑
    async addOrUpdateAdmin(){
      // this.adminForm.value.clearValidate();
      let adminInfo = this.adminForm;
      
      try {
        await adminApi.addOrUpdate(adminInfo);
        this.$message({
          message: adminInfo.id ? '修改成功' : '添加成功',
          type: 'success'
        });
        this.admin.dialogVisible = false;
        this.getAdminInfoList(adminInfo.id ? this.current : 1);
      } catch (error) {
        this.$message({
          message:  adminInfo.id ? '修改失败' : '添加失败',
          type: 'error'
        })
      }
    },

    // 4. 删除用户
    async deleteAdmin(id){
      try {
        const result = await adminApi.remove(id);
        // console.log(result);
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.getAdminInfoList(this.adminInfoList.items.length > 1 ? this.current : this.current - 1);
      } catch (error) {
        this.$message({
          message: '删除失败',
          type: 'error'
        })
      }
    },

    // 修改当前用户的状态
    handleSelectionChange(val){
      this.selectedList = val;
      // console.log(val);
    },
    // 5. 批量删除
    async deleteMoreAdmin(){
      let selectedIds = [];
      this.selectedList.forEach(item => {
        // console.log(item);
        if(item.id){
          selectedIds.push(item.id);
        }
      })
      // console.log(selectedIds);
      selectedIds.forEach(item => {
        this.deleteAdmin(item)
      })
    },

    // 多选框全选
    handleCheckAllChange(val) {
      this.checkedList = val ? this.checkboxIdsList.map(item => item.id) : [];
      this.isIndeterminate = false;
    },
    handleCheckedChange(value) {
      this.checkedList = value;
      // console.log(this.checkedList);
      this.checkAll = this.checkedList === this.checkboxIdsList.length;
      this.isIndeterminate = this.checkboxIdsList.length > 0 && this.checkedList.length < this.checkboxIdsList.length;
    },
    // 6. 获取角色数据
    async showRoleDialog(row){
      this.role.dialogVisible = true;
      this.adminForm = row;

      const result = await adminApi.getRoleInfo(row.id);
      // console.log(result);
      this.checkboxIdsList = result.data.allRolesList;
      this.checkedList = result.data.assignRoles.map(item => item.id);
    },
    // 点击保存
    async savRoleToUser(){
      let userId = this.adminForm.id;
      let roleIds = this.checkedList.join(',');
      try {
        // console.log(userId,roleIds);
        await adminApi.assignRoles(userId, roleIds);
        this.$message({
          message: '分配成功',
          type: 'success'
        });
        this.role.dialogVisible = false;
        this.getAdminInfoList();
      } catch (error) {
        this.$message({
          message: '分配失败',
          type: 'error'
        })
      }
    },
    // 点击取消
    handleCancel(){
      this.role.dialogVisible = false;
      this.checkedList = '';
    },

    // 7. 点击搜索
    search(){
      this.searchName = this.adminForm.username;
      this.getAdminInfoList(1);
    },
    // 清空
    resetSearch(){
      this.searchName = '';
      this.getAdminInfoList(1);
    }


      
  },
  computed: {
    ...mapState('admin', ['adminInfoList']),
    ...mapGetters('admin', ['items'])
  }
}
</script>

<style scoped>

</style>
